<?php

namespace addons\mental\model;

use addons\mental\model\Testlog;
use think\Config;
use think\Model;
use think\Exception;
use think\Log;
class Order extends Model
{
    // 表名
    protected $name = 'mental_order';

    // 自动写入时间戳字段
    protected $autoWriteTimestamp = 'int';

    // 定义时间戳字段名
    protected $createTime = 'createtime';
    protected $updateTime = 'updatetime';
    protected $deleteTime = false;

    // 追加属性
    protected $append = [];




    public static function getInvitationCode($phone)
    {
        static  $codeArr = [
            'L', '1', '2', 'C', '4', 'U',
            '6', '7', '8', '9', 'Y', 'Z',
            'A', 'B', '3', 'D', 'E', 'F',
            'G', 'H', 'I', '0', 'J', 'K',
            'M', 'N', 'O', 'P', 'Q', 'R',
            'S', 'T', '5', 'V', 'W', 'X',
        ];
        $code = '';
        while ($phone) {
            $mod = $phone % 36;
            $phone = (int)($phone / 36);
            $code = $codeArr[$mod] . $code;
        }
        $isCode = self::where('invitation_code', $code)->find();
        if ($isCode) {
            return self::getInvitationCode($phone);
        }
        return $code;
    }


    /**
     * Undocumented function
     * 发起订单支付
     * @param [type] $main_id
     * @param [type] $money
     * @param [type] $user_id
     * @param string $paytype
     * @return void
     */
    public static function submitOrder($money, $user_id, $main_id, $type, $test_id, $extensionId = 0, $test_num = 0)
    {

        $isOrder = self::where('test_id', $test_id)
            ->where('type', 'NEQ', 6)
            ->where('status', 'paid')
            ->find();
        if ($isOrder) {
            if ($isOrder['type'] == 1 || $isOrder['type'] == 3) {
                return false;
            }
        }




        $order = self::where('main_id', (int)$main_id)
            ->where('amount', $money)
            ->where('type', $type)
            ->where('test_id', $test_id)
            ->where('status', 'created')
            ->order('createtime', 'desc')
            ->find();

        $request = \think\Request::instance();
        $order_id = date("Ymdhis") . sprintf("%08d", $user_id) . mt_rand(1000, 9999);


        $invitation_code = '';
        if ($type == 4) {
            $invitation_code = self::getInvitationCode($order_id);
        } elseif ($type == 6) {
            $order = self::where('main_id', (int)$main_id)
                ->where('amount', $money)
                ->where('type', $type)
                ->where('user_id', $user_id)
                ->where('status', 'created')
                ->order('createtime', 'desc')
                ->find();

            if ($order) {
                $invitation_code = $order->invitation_code;
            } else {
                $invitation_code = self::getInvitationCode($order_id);
            }
        }



        if (!$order) {

            $data = [
                'order_id'   => $order_id,
                'user_id'   => $user_id,
                'main_id'   => $main_id,
                'amount'    => $money,
                'type'    => $type,
                'payamount' => 0,
                // 'ip'        => $request->ip(),
                // 'useragent' => substr($request->server('HTTP_USER_AGENT'), 0, 255),
                'status'    => 'created',
                'extensionId' => $extensionId,
                'invitation_code' => $invitation_code,
                'test_num' => $test_num,

            ];
            if ($type == 1 || $type == 2 || $type == 3 || $type == 4 || $type == 5) {
                $data['test_id'] = $test_id;
            }

            $order = self::create($data);
        } else {

            if ($order->status == 'paid') {
                return false;
            }
            $new_order['order_id'] = $order_id;
            $new_order['user_id'] = $user_id;
            $new_order['main_id'] = $main_id;
            $new_order['amount'] = $money;
            $new_order['type'] = $type;
            $new_order['status'] = 'created';
            $new_order['createtime'] = $order->createtime;
            // $new_order['ip'] = $order['ip'];
            // $new_order['useragent'] = $order['useragent'];
            $new_order['updatetime'] = time();
            $new_order['extensionId'] = $extensionId;
            $new_order['invitation_code'] = $invitation_code;
            $new_order['test_num'] = $test_num;
            if ($type == 1 || $type == 2 || $type == 3 || $type == 4 || $type == 5) {
                $new_order['test_id'] = $test_id;
            }


            // $order->delete();
            $order = self::create($new_order);
        }

        return $order->order_id;
    }

    /**
     * Undocumented function
     * 订单支付
     * @param [type] $order_id
     * @param [type] $openid
     * @param [type] $user_id
     * @param string $paytype
     * @param string $method
     * @return Object
     */
    public static function pay($user_id, $order_id, $amount, $paytype = 'wechat', $method = 'miniapp', $url = '', $openid, $attach = '')
    {
        //测试注释
        // $amount = 0.01;
        $epay = get_addon_info('epay');

        if ($epay && $epay['state']) {
            $params = [];
            if (!$openid || empty($openid)) {
                $result = self::checkOpenId($user_id, $paytype, $method, $params, $url);
                //            dump($result);
                if (!$result['status']) {
                    return $result;
                }
            }
            if ($amount<=0){
                $amount = 0.01;
            }
//            $amount = 0.01;
            $request = \think\Request::instance();
            $notifyurl = $request->root(true) . '/addons/mental/callback/epay/type/notify/paytype/' . $paytype;
            $returnurl = $method == 'wap' || $method == 'web' ? $url : $request->root(true) . '/addons/mental/callback/epay/type/return/paytype/' . $paytype;
            $params['amount'] = $amount;
            $params['orderid'] = $order_id;
            $params['type'] = $paytype;
            $params['title'] = "希言心理";
            $params['notifyurl'] = $notifyurl;
            $params['returnurl'] = $returnurl;
            $params['method'] = $method;
            $params['openid'] = $openid;
            $params['attach'] = $attach;

            return \addons\epay\library\Service::submitOrder($params);
        } else {
            throw new Exception("请先在后台安装并配置微信支付宝整合插件");
        }
    }

    public static function checkOpenId($user_id, $paytype, $method, &$params, $url)
    {
        $return = [
            'status' => true,
            'data' => ''
        ];
        if ($paytype != 'wechat') {
            return $return;
        }
        $wx_user = new WxUser();
        if ($method == 'miniapp') //微信小程序支付，需要openid
        {
            $wx = $wx_user->where('user_id', $user_id)->where('type', 1)->find();
            if (empty($wx)) {
                throw new Exception(__('No results were found'));
                return false;
            }
            $params['openid'] = $wx->openid;
        }

        if ($method == 'mp') //公众号支付，需要openid
        {
            $wx = $wx_user->where('user_id', $user_id)->where('type', 2)->find();
            if (empty($wx)) {
                return $wx_user->officialMiniLogin($url);
            }
            $params['openid'] = $wx->openid;
        }
        return $return;
    }

    /**
     * 订单回调
     * @param int    $orderid
     * @param string $payamount
     * @param string $memo
     * @return bool
     * @throws \think\exception\DbException
     */
    public static function settle($order_id, $payamount = null, $memo = '', $trade_no = '', $paytype = '')
    {
        //   var_dump($paytype);die;
        $order = self::getByOrderId($order_id);

        if (!$order) {
            return false;
        }
        // 支付回调金额和订单金额不一致 测试注释
//        if ($payamount != $order->amount) {
//            return false;
//        }

        if ($order['status'] != 'paid') {

            if ($order['type'] == 6) {
                self::invitationcode($order->main_id, $order->user_id, $order->test_num, $order->invitation_code);
            }
            \addons\mental\model\TestMainStatistics::setIncNum($order->main_id, 6, $order->extensionId);
            self::MentalCommission($order_id);
            // $testlog = Testlog::create(['user_id' => $order->user_id, 'main_id' => $order->main_id]);
            $order->payamount = $payamount;
            $order->paytime = time();
            $order->status = 'paid';
            // $order->test_id = $testlog->id;
            $order->memo = $memo;
            $order->trade_no = $trade_no;
            $order->paytype = $paytype;
            $order->save();
        }
        return true;
    }


    public static function invitationcode($main_id, $user_id, $test_num, $invitation_code)
    {
        // \think\Log::write(8989898989898);
        $where = [
            'user_id' => $user_id,
            'main_id' => $main_id,
        ];
        $data = \think\Db::name('mental_invitationcode')->where($where)->find();

        if ($data) {
            \think\Db::name('mental_invitationcode')->where(['id' => $data['id']])->setInc('num', $test_num);
        } else {
            \think\Db::name('mental_invitationcode')->insert([
                'user_id' => $user_id,
                'main_id' => $main_id,
                'invitation_code' => $invitation_code,
                'num' => $test_num,
                'createtime' => time(),
                'updatetime' => time()
            ]);
        }
        return true;
    }

    /**
     * 分佣
     */
    public static function SubCommission($order_id)
    {
        $order = self::getByOrderId($order_id);
        if (!$order) {
            return false;
        }
        $extension = \think\Db::name('mental_extension')->where('id', $order->extensionId)->where('status', 'normal')->find();
        if (!$extension) {
            return false;
        }
        $price = $order->amount * $extension['ratio'];


        //扣
        $setKoudan = self::setKoudan($extension, $order_id, $price);
        if ($setKoudan) {
            ExtensionStatistics::setDecNum(3, $order->extensionId);
            ExtensionStatistics::setDecNum(4, $order->extensionId);
            return false;
        }

        ExtensionAmount::setIncAmount($order->amount, $order->extensionId); //

        $user = \think\Db::name('user')->where('id', $extension['user_id'])->where('status', 'normal')->find();
        if ($user) {
            // \app\common\model\User::where('id', $extension['user_id'])->setInc('cumulative_gain', $price); //佣金总额
            \app\common\model\User::money($price, $extension['user_id'], '分佣');

            \think\Db::name('mental_extension')->where('id', $order->extensionId)->setInc('total_commission', $price); //佣金总额
            \think\Db::name('mental_extension')->where('id', $order->extensionId)->setInc('total_order', $order->amount); //订单总金额
            \think\Db::name('mental_extension_rewardlog')->insert([
                'order_id' => $order_id,
                'user_id' => $extension['user_id'],
                'price' => $price,
                'createtime' => time(),
                'status' => 1
            ]);
            $order->commission = $price;
            $order->save();

            return true;
        }


        return false;
    }


    /**
     * 测评分佣
     */
    public static function MentalCommission($order_id)
    {
        $order = self::getByOrderId($order_id);
        if (!$order) {
            return false;
        }

        $user = \think\Db::name('user')->where('id', $order['user_id'])->where('status', 'normal')->find();
        if ($user) {
            $parent_user = \think\Db::name('user')->where('id', $user['pid'])->where('status', 'normal')->find();
            if ($parent_user){
                //分佣比例
                if ($parent_user['commission_rate']>0){
                    $commission_rate = $parent_user['commission_rate']>0;
                }else{
                    $commission_rate = Config::get('site.commission_rate');
                }
                $commission_rate = bcMath($commission_rate,100,'/');
                Log::info($commission_rate);
                $price = bcMath($order->amount,$commission_rate,'*');
                $memo = '测评推广分佣 比例'.$commission_rate.'% <br/>订单编号:'.$order_id;
                Log::info('测评推广分佣:'.$memo);

                //给到余额
                \app\common\model\User::money($price,$parent_user['id'],$memo,5);
//                $parent_user->setInc('cumulative_gain',$price);
                // \think\Db::name('user')->where('id', $parent_user['id'])->setInc('cumulative_gain',$price);
                return true;
            }

        }


        return false;
    }
    /**
     * true=扣,false=不扣
     */
    public static function setKoudan($extension, $order_id, $price)
    {
        $koudanData = \think\Db::name('koudan')->where('user_id', $extension['user_id'])->find();
        if ($koudanData) {
            if ($koudanData['rule_num'] == 0) {
                return false;
            }

            if ($koudanData['num1'] == 100) {
                $num1 = 1;
                $num  = self::getNumstr($koudanData['rule_num']);
            } else {
                $num  = $koudanData['num'];
                $num1 = $koudanData['num1'] + 1;
            }

            if (!$num) {
                $num  = self::getNumstr($koudanData['rule_num']);
            }

            \think\Db::name('koudan')->where('id', $koudanData['id'])->update(['num' => $num, 'num1' => $num1]);


            $numArr = explode(',', $num);
            if (in_array($num1, $numArr)) {
                \think\Db::name('koudan_log')->insert(['order_id' => $order_id, 'user_id' => $extension['user_id'], 'price' => $price, 'createtime' => time(), 'extension_id' => $extension['id']]);
                \think\Db::name('mental_extension')->where('id', $extension['id'])->setInc('total_deduction', $price); //佣金总额
                \think\Db::name('mental_order')->where('order_id', $order_id)->update(['extensionId' => 0]);
                return true;
            }
        }

        return false;
    }

    public static function getNumstr($rule_num)
    {
        $numbers = range(1, 100);
        //shuffle 将数组顺序随即打乱 
        shuffle($numbers);
        //array_slice 取该数组中的某一段 
        $result = array_slice($numbers, 0, $rule_num);
        return implode(',', $result);
    }


    public function User()
    {
        return $this->hasOne('User', 'id', 'user_id')->bind('avatar,nickname');
    }
}
